package cn.edu.buu.hospital.web;
import cn.edu.buu.hospital.entity.User;
import cn.edu.buu.hospital.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 跳转到新增用户页面
    @GetMapping("/toAdd")
    public String toAdd() {
        return "backend/user/add";
    }

    // 新增用户
    @PostMapping("/add")
    public String add(User user, Model model) {
        try {
            // 设置创建时间
            userService.add(user);
            return "redirect:find";
        } catch (Exception e) {
            model.addAttribute("error", "新增失败: " + e.getMessage());
            model.addAttribute("user", user);
            return "backend/user/add";
        }
    }

    // 查询用户列表
    @RequestMapping(value = "/find", method = {RequestMethod.GET, RequestMethod.POST})
    public String find(Model model,
                      @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                      User condition) {
        int pageSize = 5;
        PageInfo<User> pageInfo = userService.find(pageNum, pageSize, condition);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("condition", condition);
        return "backend/user/list";
    }

    // 根据ID查询用户（用于编辑）
    @GetMapping("/findById")
    public String findById(@RequestParam("userId") Long userId, Model model) {
        // 根据ID查询用户信息
        User user = userService.findById(userId);
        if (user == null) {
            user = new User();
            user.setUserid(userId);
        }
        model.addAttribute("user", user);
        return "backend/user/edit";
    }

    // 修改用户信息
    @PostMapping("/modify")
    public String modify(User user, Model model) {
        try {
            userService.modify(user);
            return "redirect:find";
        } catch (Exception e) {
            model.addAttribute("error", "修改失败: " + e.getMessage());
            model.addAttribute("user", user);
            return "backend/user/edit";
        }
    }

    // 删除用户
    @GetMapping("/removeById")
    public String removeById(@RequestParam("userId") Long userId) {
        userService.removeById(userId);
        return "redirect:find";
    }
    
    // 查看个人信息
    @GetMapping("/profile")
    public String profile(HttpSession session, Model model, 
                     @RequestParam(value = "editMode", required = false, defaultValue = "false") boolean editMode) {
        // 从session中获取登录用户信息
        User loginAdmin = (User) session.getAttribute("loginAdmin");
        if (loginAdmin != null) {
            // 根据ID查询完整的用户信息
            User user = userService.findById(loginAdmin.getUserid());
            model.addAttribute("user", user);
            model.addAttribute("editMode", editMode);
        }
        return "backend/user/profile"; // 修正路径，从admin改为user
    }
    
    // 更新个人信息
    @PostMapping("/updateProfile")
    public String updateProfile(User user, 
                               @RequestParam(value = "file", required = false) MultipartFile file, 
                               HttpSession session, Model model) throws Exception {
        try {
            // 如果有上传新头像，则处理文件
            if (file != null && !file.isEmpty()) {
                ServletContext application = session.getServletContext();
                String serverRealPath = application.getRealPath("statics/images/adminHead/");
                String originalFilename = file.getOriginalFilename();
                String fileExtendsName = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + fileExtendsName;
                Path path = Paths.get(serverRealPath, fileName);
                file.transferTo(path);
                user.setHeadpic(fileName);
                // 更新session中的用户头像
                User loginAdmin = (User) session.getAttribute("loginAdmin");
                if (loginAdmin != null) {
                    loginAdmin.setHeadpic(fileName);
                    session.setAttribute("loginAdmin", loginAdmin);
                }
            }
            
            // 执行更新操作
            userService.modify(user);
            
            // 重新查询用户信息以获取最新数据
            User updatedUser = userService.findById(user.getUserid());
            model.addAttribute("user", updatedUser);
            model.addAttribute("success", "个人信息更新成功！");
        } catch (Exception e) {
            model.addAttribute("error", "更新失败: " + e.getMessage());
        }
        return "backend/user/profile";
    }
}